<template>
  <div class="job-detail-page">
    <div class="container">
      <el-row :gutter="20" v-loading="loading">
        <!-- 左侧主内容 -->
        <el-col :xs="24" :md="16">
          <!-- 面包屑导航 -->
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item :to="{ path: '/jobs' }">职位列表</el-breadcrumb-item>
              <el-breadcrumb-item>{{ job.title }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          
          <!-- 职位信息卡片 -->
          <div class="job-card" v-if="job.id">
            <div class="job-header">
              <div class="company-logo">
                <div v-if="job.companyLogo" class="logo-image">
                  <img :src="job.companyLogo" :alt="job.companyName">
                </div>
                <div v-else class="logo-placeholder">
                  {{ job.companyName ? job.companyName.substring(0, 1) : 'C' }}
                </div>
              </div>
              <div class="job-info">
                <h1 class="job-title">{{ job.title }}</h1>
                <div class="job-company">{{ job.companyName }}</div>
                <div class="job-meta">
                  <span class="job-location">
                    <el-icon><location /></el-icon>
                    {{ job.city }}
                  </span>
                  <span class="job-experience">
                    <el-icon><user /></el-icon>
                    {{ job.experienceRequired }}
                  </span>
                  <span class="job-education">
                    <el-icon><reading /></el-icon>
                    {{ job.educationRequired }}
                  </span>
                </div>
              </div>
              <div class="job-salary">
                <div class="salary-amount">{{ job.salaryRange }}</div>
                <div class="post-date">发布于 {{ formatTime(job.createTime) }}</div>
              </div>
            </div>
            
            <!-- 操作按钮 -->
            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="large" 
                :disabled="isApplied"
                @click="applyForJob"
              >
                {{ isApplied ? '已申请' : '申请职位' }}
              </el-button>
              <el-button 
                type="success" 
                size="large"
                plain
                @click="startChat"
              >
                在线沟通
              </el-button>
            </div>
          </div>
          
          <!-- 职位详情 -->
          <div class="job-detail-sections" v-if="job.id">
            <!-- 职位描述 -->
            <div class="detail-section">
              <h2 class="section-title">职位描述</h2>
              <div class="section-content rich-text">
                <p>{{ job.description }}</p>
              </div>
            </div>
            
            <!-- 职责要求 -->
            <div class="detail-section">
              <h2 class="section-title">任职要求</h2>
              <div class="section-content rich-text">
                <p>{{ job.requirement }}</p>
              </div>
            </div>
            
            <!-- 工作地址 -->
            <div class="detail-section">
              <h2 class="section-title">工作地址</h2>
              <div class="section-content">
                <div class="address-info">
                  <div class="address-icon">
                    <el-icon><Location /></el-icon>
                  </div>
                  <div class="address-detail">
                    <p class="address-text">{{ job.city }} {{ job.address}}</p>
                  
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 相似职位推荐 -->
          <div class="similar-jobs">
            <h2 class="section-title">相似职位推荐</h2>
            <div class="job-list" v-if="similarJobs.length > 0">
              <job-card 
                v-for="similarJob in similarJobs" 
                :key="similarJob.id" 
                :job="similarJob"
                class="job-item"
              />
            </div>
            <el-empty v-else description="暂无相似职位推荐" />
          </div>
        </el-col>
        
        <!-- 右侧公司信息 -->
        <el-col :xs="24" :md="8">
          <!-- 公司信息卡片 -->
          <div class="company-card" v-if="job.id">
            <div class="company-header">
              <div class="company-logo">
                <div v-if="job.companyLogo" class="logo-image">
                  <img :src="job.companyLogo" :alt="job.companyName">
                </div>
                <div v-else class="logo-placeholder">
                  {{ job.companyName ? job.companyName.substring(0, 1) : 'C' }}
                </div>
              </div>
              <div class="company-info">
                <h3 class="company-name">{{ job.companyName }}</h3>
                <div class="company-meta">
                  <span>互联网/科技</span>
                  <span>500-1000人</span>
                </div>
              </div>
            </div>
            
            <div class="company-desc">
              {{ job.companyName }} 是一家致力于技术创新的企业，提供优质的工作环境和有竞争力的薪资待遇。
            </div>
            
            <div class="company-footer">
              <el-button type="info" plain @click="viewCompany">查看公司主页</el-button>
            </div>
          </div>
          
          <!-- 招聘者信息 -->
          <div class="recruiter-card" v-if="job.recruiterInfo">
            <h3 class="card-title">招聘者信息</h3>
            <div class="recruiter-info">
              <div class="recruiter-avatar">
                <img v-if="job.recruiterInfo && job.recruiterInfo.avatar" :src="getFullAvatarURL(job.recruiterInfo.avatar)" alt="招聘者头像" class="avatar-image">
                <span v-else class="avatar-text">{{ job.recruiterInfo && job.recruiterInfo.realName ? job.recruiterInfo.realName.substring(0, 1) : 'R' }}</span>
              </div>
              <div class="recruiter-detail">
                <div class="recruiter-name">{{ job.recruiterInfo ? job.recruiterInfo.realName || '招聘专员' : '招聘专员' }}</div>
                <div class="recruiter-position">{{ job.recruiterInfo ? job.recruiterInfo.position || '招聘负责人' : '招聘负责人' }}</div>
                <div class="recruiter-response">
                  <el-icon><chat-dot-round /></el-icon>
                  <span>平均响应时间: 1天内</span>
                </div>
              </div>
            </div>
            <div class="recruiter-footer">
              <el-button type="success" @click="startChat">与招聘者沟通</el-button>
            </div>
          </div>
          
          <!-- 职位统计 -->
          <div class="stats-card" v-if="job.id">
            <h3 class="card-title">职位统计</h3>
            <ul class="stats-list">
              
              <li class="stats-item">
                <div class="stats-label">发布时间</div>
                <div class="stats-value">{{ formatFullTime(job.createTime) }}</div>
              </li>
            </ul>
          </div>
        </el-col>
      </el-row>
      
      <!-- 申请职位对话框 -->
      <el-dialog
        v-model="applyDialogVisible"
        title="申请职位"
        width="500px"
      >
        <div class="apply-form">
          <template v-if="resumes.length > 0">
            <p class="apply-tip">请选择您要投递的简历</p>
            <el-form :model="applyForm" label-position="top">
              <el-form-item label="选择简历">
                <el-radio-group v-model="applyForm.resumeId">
                  <div v-for="resume in resumes" :key="resume.id" class="resume-item">
                    <el-radio :label="resume.id">
                      {{ resume.name || resume.title }} 
                      <el-tag size="small">{{ formatDate(resume.updateTime) }}</el-tag>
                    </el-radio>
                  </div>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="求职意向">
                <el-input 
                  v-model="applyForm.message" 
                  type="textarea" 
                  rows="3"
                  placeholder="请简要描述您的求职意向和对该职位的期望..."
                />
              </el-form-item>
            </el-form>
          </template>
          
          <el-empty v-else description="您还没有简历，请先创建简历">
            <template #extra>
              <el-button type="primary" @click="createResume">创建简历</el-button>
            </template>
          </el-empty>
        </div>
        
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="applyDialogVisible = false">取消</el-button>
            <el-button 
              type="primary"
              :disabled="!applyForm.resumeId || resumes.length === 0"
              :loading="submitting"
              @click="submitApplication"
            >
              提交申请
            </el-button>
          </span>
        </template>
      </el-dialog>
      
      <!-- 在线沟通对话框 -->
      <el-dialog
        v-model="chatDialogVisible"
        title="在线沟通"
        width="800px"
        class="chat-dialog"
      >
        <div class="chat-container">
          <div class="chat-header">
            <div class="chat-title">
              <span class="job-chat-title">{{ job.title }}</span>
              <span class="company-chat-name">{{ job.companyName }}</span>
            </div>
          </div>
          
          <div class="chat-body">
            <!-- 左侧求职者列表(招聘者视角) -->
            <div v-if="isRecruiter" class="applicant-sidebar">
              <div class="sidebar-header">
                <div class="sidebar-title">求职者列表</div>
              </div>
              
              <div class="applicant-list-sidebar">
                <div v-for="applicant in chatApplicants" 
                     :key="applicant.senderId" 
                     class="applicant-item-sidebar"
                     :class="{ 'active': currentChatUser && currentChatUser.senderId === applicant.senderId }"
                     @click="switchChatUser(applicant)">
                  <div class="applicant-avatar">
                    <img v-if="applicant.avatar" :src="getFullAvatarURL(applicant.avatar)" alt="求职者头像" class="avatar-image">
                    <span v-else>{{ applicant.senderName ? applicant.senderName.substring(0, 1) : 'U' }}</span>
                  </div>
                  <div class="applicant-info">
                    <div class="applicant-name">{{ applicant.senderName }}</div>
                    <div class="applicant-time">{{ formatMessageTime(applicant.lastMessageTime) }}</div>
                  </div>
                </div>
                
                <el-empty v-if="chatApplicants.length === 0" 
                         description="暂无求职者沟通记录" 
                         :image-size="100" />
              </div>
            </div>
            
            <!-- 左侧招聘者信息(求职者视角) -->
            <div v-if="!isRecruiter" class="recruiter-sidebar">
              <div class="sidebar-header">
                <div class="sidebar-title">招聘者信息</div>
              </div>
              
              <div class="recruiter-profile">
                <div class="recruiter-avatar">
                  <img v-if="job.recruiterInfo && job.recruiterInfo.avatar" :src="getFullAvatarURL(job.recruiterInfo.avatar)" alt="招聘者头像" class="avatar-image">
                  <span v-else class="avatar-text">{{ job.recruiterInfo && job.recruiterInfo.realName ? job.recruiterInfo.realName.substring(0, 1) : 'R' }}</span>
                </div>
                <div class="recruiter-info">
                  <div class="recruiter-name">{{ job.recruiterInfo ? job.recruiterInfo.realName || '招聘专员' : '招聘专员' }}</div>
                  <div class="recruiter-position">{{ job.recruiterInfo ? job.recruiterInfo.position || '招聘负责人' : '招聘负责人' }}</div>
                </div>
              </div>
              
              <div class="job-brief">
                <div class="brief-header">职位信息</div>
                <div class="brief-title">{{ job.title }}</div>
                <div class="brief-company">{{ job.companyName }}</div>
                <div class="brief-salary">{{ job.salaryRange }}</div>
              </div>
            </div>
            
            <!-- 右侧聊天内容 -->
            <div class="chat-content">
              <!-- 当前对话对象提示(仅招聘者) -->
              <div v-if="isRecruiter && currentChatUser" class="current-chat-indicator">
                当前正在与 <span class="highlight-user">{{ currentChatUser.senderName }}</span> 对话
              </div>
            
              <div class="chat-messages" ref="chatMessagesRef">
                <div v-if="chatMessages.length > 0" class="message-list">
                  <div 
                    v-for="(message, index) in filteredMessages" 
                    :key="index"
                    :class="[
                      'message-item', 
                      { 
                        'self': message.senderId === currentUserId,
                      }
                    ]"
                  >
                    <div class="message-avatar">
                      <img v-if="message.avatar" :src="getFullAvatarURL(message.avatar)" alt="用户头像" class="avatar-image">
                      <span v-else>{{ message.senderName ? message.senderName.substring(0, 1) : 'U' }}</span>
                    </div>
                    <div class="message-content">
                      <div class="message-sender">{{ message.senderName }}</div>
                      <div class="message-text">{{ message.content }}</div>
                      <div class="message-time">{{ formatMessageTime(message.createTime) }}</div>
                    </div>
                  </div>
                </div>
                
                <el-empty v-else description="暂无沟通记录，发送一条消息开始沟通" />
              </div>
              
              <div class="chat-input">
                <el-input
                  v-model="messageInput"
                  type="textarea"
                  rows="3"
                  placeholder="输入消息..."
                  @keyup.enter.ctrl="sendMessage"
                />
                <div class="input-actions">
                  <span class="input-tip">按 Ctrl + Enter 发送</span>
                  <el-button 
                    type="primary" 
                    :disabled="!messageInput.trim()"
                    @click="sendMessage"
                  >
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUpdated, nextTick, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getJobDetail, getJobChatMessages, sendJobChatMessage, applyJob, getJobs, checkJobApplied } from '@/api/job'
import { getResumeList } from '@/api/resume'
import JobCard from '@/components/job/JobCard.vue'
import { getFullAvatarURL } from '@/utils/common'

const route = useRoute()
const router = useRouter()
const jobId = ref(route.params.id)

// 页面数据
const job = ref({})
const similarJobs = ref([])
const loading = ref(true)
const isApplied = ref(false)
const isCollected = ref(false)
const resumes = ref([])
const currentUserId = ref(null)
const isRecruiter = ref(false)
const isJobPoster = ref(false)
const currentChatUser = ref(null)

// 对话框状态
const applyDialogVisible = ref(false)
const chatDialogVisible = ref(false)
const submitting = ref(false)
const sending = ref(false)
const chatMessagesRef = ref(null)
const chatApplicants = ref([])

// 申请表单
const applyForm = reactive({
  resumeId: '',
  message: ''
})

// 聊天相关
const chatMessages = ref([])
const messageInput = ref('')

// 当前对话消息过滤
const filteredMessages = computed(() => {
  if (!isRecruiter.value) {
    // 求职者视角：只显示自己和招聘者之间的消息
    return chatMessages.value.filter(msg => 
      // 求职者发给招聘者的消息
      (msg.senderId === currentUserId.value && msg.receiverId === job.value.userId) ||
      // 招聘者发给求职者的消息
      (msg.senderId === job.value.userId && msg.receiverId === currentUserId.value)
    );
  } else if (currentChatUser.value) {
    // 招聘者视角：只显示与当前选中求职者的对话
    const selectedJobSeekerId = currentChatUser.value.senderId;
    
    return chatMessages.value.filter(msg => 
      // 招聘者发给当前选中求职者的消息
      (msg.senderId === currentUserId.value && msg.receiverId === selectedJobSeekerId) ||
      // 当前选中求职者发给招聘者的消息
      (msg.senderId === selectedJobSeekerId && msg.receiverId === currentUserId.value)
    );
  } else {
    // 未选择求职者时，不显示任何消息
    return [];
  }
});

// 获取职位详情
const fetchJobDetail = async () => {
  loading.value = true
  
  try {
    const response = await getJobDetail(jobId.value)
    if (response && response.data) {
      job.value = response.data
      
      // 获取类似职位
      fetchSimilarJobs()
      
      // 检查是否已申请
      checkApplicationStatus()
    }
  } catch (error) {
    ElMessage.error('获取职位详情失败，请稍后再试')
    console.error('获取职位详情失败', error)
  } finally {
    loading.value = false
  }
}

// 获取类似职位
const fetchSimilarJobs = async () => {
  try {
    if (!job.value.id) return
    
    // 模拟获取相似职位，实际中应该有专门的接口
    const response = await getJobs({
      page: 1,
      size: 3,
      keyword: job.value.title.split(' ')[0], // 简单地用职位名称的第一个词作为关键字
      excludeId: job.value.id
    })
    
    if (response && response.data) {
      similarJobs.value = response.data.records || []
    }
  } catch (error) {
    console.error('获取相似职位失败', error)
  }
}

// 检查职位申请状态
const checkApplicationStatus = async () => {
  try {
    // 只有当用户已登录时才检查
    const token = localStorage.getItem('token')
    if (!token) return
    
    const response = await checkJobApplied(jobId.value)
    if (response && response.code === 200) {
      isApplied.value = response.data
    }
  } catch (error) {
    console.error('检查申请状态失败', error)
  }
}

// 申请职位
const applyForJob = async () => {
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再申请职位')
    router.push({
      path: '/auth/login',
      query: { redirect: `/jobs/${jobId.value}` }
    })
    return
  }
  
  // 检查用户角色
  const userStr = localStorage.getItem('user')
  if (userStr) {
    const user = JSON.parse(userStr)
    currentUserId.value = user.id
    
    // 后端中 role=0 表示求职者, role=1 表示招聘者, role=2 表示管理员
    // 前端中 role=3 表示求职者, role=2 表示招聘者
    // 判断用户是否为求职者
    if (user.role !== 0 && user.role !== 3) {
      ElMessage.warning('只有求职者可以申请职位')
      return
    }
  }
  
  // 打开申请对话框
  applyDialogVisible.value = true
  
  // 获取用户的真实简历列表
  try {
    const response = await getResumeList()
    if (response && response.code === 200) {
      resumes.value = response.data || []
      
      // 默认选择第一份简历
      if (resumes.value.length > 0) {
        applyForm.resumeId = resumes.value[0].id
      }
    } else {
      ElMessage.error(response?.message || '获取简历列表失败')
    }
  } catch (error) {
    console.error('获取简历列表失败', error)
    ElMessage.error('获取简历列表失败，请稍后再试')
  }
}

// 提交职位申请
const submitApplication = async () => {
  if (!applyForm.resumeId) {
    ElMessage.warning('请选择要投递的简历')
    return
  }
  
  submitting.value = true
  
  try {
    const response = await applyJob(jobId.value, {
      resumeId: applyForm.resumeId
      // message字段后端不处理，暂时移除
    })
    
    if (response && response.code === 200) {
      ElMessage.success('申请成功，请等待招聘方查看')
      applyDialogVisible.value = false
      
      // 设置为已申请状态
      isApplied.value = true
      
      // 更新申请数量
      if (job.value.applications !== undefined) {
        job.value.applications += 1
      }
    } else {
      ElMessage.error(response?.message || '申请失败，请稍后再试')
    }
  } catch (error) {
    console.error('申请职位失败', error)
    
    // 如果是已申请过的错误，更新状态
    if (error.response && error.response.data && error.response.data.message === '您已经申请过该职位') {
      isApplied.value = true
      ElMessage.warning('您已经申请过该职位')
      applyDialogVisible.value = false
    } else {
      ElMessage.error('申请失败，请稍后再试')
    }
  } finally {
    submitting.value = false
  }
}

// 创建简历
const createResume = () => {
  applyDialogVisible.value = false
  router.push('/resumes/edit')
}

// 收藏职位
const toggleCollection = () => {
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再收藏职位')
    router.push({
      path: '/auth/login',
      query: { redirect: `/jobs/${jobId.value}` }
    })
    return
  }
  
  // 切换收藏状态
  isCollected.value = !isCollected.value
  
  // 显示提示
  ElMessage.success(isCollected.value ? '收藏成功' : '已取消收藏')
  
  // 实际应该调用后端接口
}

// 查看公司主页
const viewCompany = () => {
  router.push(`/companies/${job.value.companyId}`)
}

// 在地图应用中打开地址
const openMap = () => {
  // 处理地址字符串，确保没有null或undefined值
  const city = job.value.city || '';
  const address = job.value.address || '';
  
  // 如果没有任何地址信息，不进行操作
  if (!city && !address) {
    ElMessage.warning('未找到有效的地址信息');
    return;
  }
  
  // 构建完整的地址字符串
  const fullAddress = city + (address ? ' ' + address : '');
  
  // 尝试使用百度地图打开
  const baiduMapUrl = `https://api.map.baidu.com/geocoder?address=${encodeURIComponent(fullAddress)}&output=html`;
  window.open(baiduMapUrl, '_blank');
}

// 开始聊天
const startChat = async () => {
  console.log('开始聊天功能被调用');
  
  // 检查用户是否登录
  const token = localStorage.getItem('token')
  if (!token) {
    ElMessage.warning('请先登录后再开始沟通')
    router.push({
      path: '/auth/login',
      query: { redirect: `/jobs/${jobId.value}` }
    })
    return
  }
  
  // 获取用户ID和角色
  const userStr = localStorage.getItem('user')
  if (userStr) {
    const user = JSON.parse(userStr)
    currentUserId.value = user.id
    console.log('当前用户ID:', currentUserId.value);
    console.log('当前用户角色:', user.role);
    
    // 检查是否为招聘者
    isRecruiter.value = (user.role === 1)
    isJobPoster.value = (user.id === job.value.userId)
    console.log('是否是招聘者:', isRecruiter.value);
    console.log('是否是职位发布者:', isJobPoster.value);
  }
  
  // 打开聊天对话框
  chatDialogVisible.value = true
  console.log('聊天对话框已打开');
  
  // 获取聊天记录
  try {
    console.log('正在获取聊天记录，职位ID:', jobId.value);
    await fetchChatMessages()
  } catch (error) {
    console.error('获取聊天记录失败:', error);
    ElMessage.error('获取聊天记录失败: ' + (error.message || '未知错误'));
  }
}

// 获取聊天记录
const fetchChatMessages = async () => {
  try {
    console.log('调用getJobChatMessages API, 职位ID:', jobId.value);
    const response = await getJobChatMessages(jobId.value, {
      page: 1,
      size: 50
    })
    
    console.log('获取聊天记录响应:', response);
    
    if (response && response.data) {
      // 获取原始消息记录
      const records = response.data.records || []
      console.log('获取到聊天记录数量:', records.length);
      
      // 添加日志查看消息结构
      if (records.length > 0) {
        console.log('原始聊天消息示例:', records[0]);
      } else {
        console.log('没有聊天记录');
      }
      
      // 检查并补充receiverId字段
      chatMessages.value = records.map(msg => {
        // 如果消息已经有receiverId字段，直接使用
        if (msg.receiverId) {
          return msg;
        }
        
        // 否则补充receiverId字段
        const newMsg = { ...msg };
        
        // 确定消息的receiverId
        if (newMsg.senderId === currentUserId.value) {
          // 当前用户发送的消息
          // 找出同一对话中对方回复的消息，获取其senderId作为receiverId
          const replyMsg = records.find(m => 
            m.senderId !== currentUserId.value && 
            m.createTime > newMsg.createTime
          );
          
          if (replyMsg) {
            // 如果有回复，则接收者是回复的发送者
            newMsg.receiverId = replyMsg.senderId;
          } else {
            // 没有回复，如果是求职者，则接收者是职位发布者
            // 如果是招聘者，接收者需要从其他信息确定
            if (isRecruiter.value) {
              // 招聘者发送的消息，但没找到回复，暂时无法确定接收者
              // 这种情况通常不应该发生，因为招聘者发消息时需要选择对话对象
              newMsg.receiverId = null;
            } else {
              // 求职者发送的消息，接收者是职位发布者
              newMsg.receiverId = job.value.userId;
            }
          }
        } else {
          // 他人发送的消息，接收者是当前用户
          newMsg.receiverId = currentUserId.value;
        }
        
        return newMsg;
      });
      
      // 添加日志查看处理后的消息
      if (chatMessages.value.length > 0) {
        console.log('处理后的聊天消息示例:', chatMessages.value[0]);
      }
      
      // 更新当前聊天对象（如果是招聘者）
      if (isRecruiter.value && chatMessages.value.length > 0) {
        // 获取所有不同的申请者
        updateChatApplicants();
        
        // 按时间降序排序消息
        const sortedMessages = [...chatMessages.value].sort((a, b) => {
          return new Date(b.createTime) - new Date(a.createTime);
        });
        
        // 找到最新的非当前用户发送的消息
        const latestOtherParty = sortedMessages.find(msg => msg.senderId !== currentUserId.value);
        
        if (latestOtherParty) {
          currentChatUser.value = {
            senderId: latestOtherParty.senderId,
            senderName: latestOtherParty.senderName
          };
        } else {
          ElMessage.error('无法确定消息接收者');
          return;
        }
      }
      
      // 滚动到底部
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    ElMessage.error('获取聊天记录失败')
    console.error('获取聊天记录失败', error)
  }
}

// 更新聊天申请者列表
const updateChatApplicants = () => {
  if (!isRecruiter.value || chatMessages.value.length === 0) return;
  
  const applicants = new Map();
  
  // 遍历所有消息，找出所有不同的发送者（排除当前用户）
  chatMessages.value.forEach(msg => {
    if (msg.senderId !== currentUserId.value) {
      if (!applicants.has(msg.senderId)) {
        applicants.set(msg.senderId, {
          senderId: msg.senderId,
          senderName: msg.senderName,
          lastMessageTime: msg.createTime
        });
      } else {
        // 更新最后消息时间（如果更新）
        const existingApplicant = applicants.get(msg.senderId);
        if (new Date(msg.createTime) > new Date(existingApplicant.lastMessageTime)) {
          existingApplicant.lastMessageTime = msg.createTime;
        }
      }
    }
  });
  
  // 转换为数组并按最后消息时间排序
  chatApplicants.value = Array.from(applicants.values()).sort((a, b) => {
    return new Date(b.lastMessageTime) - new Date(a.lastMessageTime);
  });
}

// 切换聊天用户
const switchChatUser = (applicant) => {
  currentChatUser.value = applicant;
  
  // 过滤显示与当前选中用户的聊天记录
  // 注意：这里我们不实际过滤消息，而是在UI中通过CSS区分当前对话的消息
  
  ElMessage.success(`已切换到与 ${applicant.senderName} 的对话`);
}

// 发送消息
const sendMessage = async () => {
  console.log('发送消息被调用');
  if (!messageInput.value.trim()) {
    console.log('消息内容为空，不发送');
    return
  }
  
  // 根据当前用户角色确定接收者ID
  try {
    console.log('准备发送消息');
    // 加载状态
    sending.value = true
    
    // 构建消息内容
    let receiverId = null
    
    // 如果当前用户是招聘者且是职位发布者，接收者是求职者
    if (isRecruiter.value && isJobPoster.value) {
      receiverId = currentChatUser.value ? currentChatUser.value.senderId : null;
      console.log('招聘者发送消息给求职者，接收者ID:', receiverId);
    } 
    // 如果是求职者，接收者是职位发布者
    else {
      receiverId = job.value.userId
      console.log('求职者发送消息给招聘者，接收者ID:', receiverId);
    }
    
    if (!receiverId) {
      console.error('未能确定消息接收者ID');
      ElMessage.error('未能确定消息接收者');
      sending.value = false
      return
    }
    
    // 组装消息对象
    const messageData = {
      receiverId: receiverId,
      content: messageInput.value
    }
    
    console.log('消息数据:', messageData);
    console.log('发送到的职位ID:', jobId.value);
    
    // 发送消息请求
    const response = await sendJobChatMessage(jobId.value, messageData)
    console.log('发送消息响应:', response);
    
    // 发送成功，清空输入框，刷新消息列表
    if (response) {
      messageInput.value = ''
      await fetchChatMessages()
      // 滚动到最新消息
      scrollToBottom()
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    ElMessage.error('发送消息失败: ' + (error.message || '未知错误'));
  } finally {
    sending.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  
  const date = new Date(timeStr)
  const now = new Date()
  
  // 计算时间差（毫秒）
  const diff = now.getTime() - date.getTime()
  
  // 转换为天数
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return formatFullTime(timeStr)
  }
}

// 格式化完整时间
const formatFullTime = (timeStr) => {
  if (!timeStr) return ''
  
  const date = new Date(timeStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

// 格式化消息时间
const formatMessageTime = (timeStr) => {
  if (!timeStr) return ''
  
  const date = new Date(timeStr)
  return `${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

// 补零函数
const padZero = (num) => {
  return num < 10 ? `0${num}` : num
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())}`
}

// 页面挂载时获取数据
onMounted(() => {
  fetchJobDetail()
})

// 更新后滚动聊天到底部
onUpdated(() => {
  if (chatDialogVisible.value) {
    scrollToBottom()
  }
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.css';

// 添加混合函数
@mixin responsive($breakpoint) {
  @if $breakpoint == sm {
    @media (max-width: 576px) {
      @content;
    }
  } @else if $breakpoint == md {
    @media (max-width: 768px) {
      @content;
    }
  } @else if $breakpoint == lg {
    @media (max-width: 992px) {
      @content;
    }
  } @else if $breakpoint == xl {
    @media (max-width: 1200px) {
      @content;
    }
  }
}

@mixin flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.job-detail-page {
  padding: var(--spacing-xl) 0;
}

// 面包屑
.breadcrumb {
  margin-bottom: var(--spacing-lg);
}

// 职位信息卡片
.job-card {
  background-color: #fff;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
  
  .job-header {
    display: flex;
    margin-bottom: var(--spacing-lg);
    
    @include responsive(sm) {
      flex-direction: column;
    }
    
    .company-logo {
      width: 80px;
      height: 80px;
      flex-shrink: 0;
      margin-right: var(--spacing-lg);
      border-radius: var(--border-radius);
      overflow: hidden;
      background-color: var(--light-color);
      
      @include responsive(sm) {
        margin-bottom: var(--spacing-md);
      }
      
      .logo-image {
        width: 100%;
        height: 100%;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .logo-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 2.5rem;
        font-weight: 700;
        color: var(--primary-color);
      }
    }
    
    .job-info {
      flex-grow: 1;
      margin-right: var(--spacing-lg);
      
      @include responsive(sm) {
        margin-right: 0;
        margin-bottom: var(--spacing-md);
      }
    }
    
    .job-title {
      font-size: 1.6rem;
      font-weight: 600;
      margin: 0 0 var(--spacing-xs);
      color: var(--text-primary);
    }
    
    .job-company {
      font-size: 1.1rem;
      color: var(--text-secondary);
      margin-bottom: var(--spacing-sm);
    }
    
    .job-meta {
      display: flex;
      flex-wrap: wrap;
      
      .job-location,
      .job-experience,
      .job-education {
        display: flex;
        align-items: center;
        margin-right: var(--spacing-md);
        color: var(--text-secondary);
        
        .el-icon {
          margin-right: var(--spacing-xs);
          color: var(--text-light);
        }
      }
    }
    
    .job-salary {
      text-align: right;
      
      @include responsive(sm) {
        text-align: left;
      }
      
      .salary-amount {
        font-size: 1.6rem;
        font-weight: 600;
        color: var(--accent-color);
        margin-bottom: var(--spacing-xs);
      }
      
      .post-date {
        color: var(--text-light);
        font-size: 0.9rem;
      }
    }
  }
  
  .action-buttons {
    display: flex;
    
    @include responsive(sm) {
      flex-direction: column;
      
      .el-button {
        margin-bottom: var(--spacing-sm);
        margin-left: 0;
      }
    }
  }
}

// 职位详情区域
.job-detail-sections {
  margin-bottom: var(--spacing-xl);
  
  .detail-section {
    background-color: #fff;
    border-radius: var(--border-radius);
    box-shadow: var(--box-shadow);
    padding: var(--spacing-lg);
    margin-bottom: var(--spacing-lg);
    
    .section-title {
      font-size: 1.25rem;
      font-weight: 600;
      margin: 0 0 var(--spacing-md);
      padding-bottom: var(--spacing-sm);
      border-bottom: 1px solid var(--border-color);
    }
    
    .rich-text {
      line-height: 1.8;
      color: var(--text-secondary);
      
      p {
        margin-bottom: var(--spacing-md);
      }
    }
    
    .address-info {
      display: flex;
      align-items: center;
      margin-top: var(--spacing-md);
      
      .address-icon {
        margin-right: var(--spacing-md);
      }
      
      .address-detail {
        flex-grow: 1;
        
        .address-text {
          margin-bottom: var(--spacing-sm);
        }
        
        .map-button {
          margin-top: var(--spacing-sm);
        }
      }
    }
  }
}

// 相似职位
.similar-jobs {
  margin-bottom: var(--spacing-xl);
  
  .section-title {
    font-size: 1.25rem;
    font-weight: 600;
    margin: 0 0 var(--spacing-lg);
  }
  
  .job-item {
    margin-bottom: var(--spacing-md);
  }
}

// 右侧卡片通用样式
.company-card,
.recruiter-card,
.stats-card {
  background-color: #fff;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
}

// 公司卡片
.company-card {
  .company-header {
    display: flex;
    align-items: center;
    margin-bottom: var(--spacing-md);
    
    .company-logo {
      width: 60px;
      height: 60px;
      flex-shrink: 0;
      margin-right: var(--spacing-md);
      border-radius: var(--border-radius);
      overflow: hidden;
      background-color: var(--light-color);
      
      .logo-image {
        width: 100%;
        height: 100%;
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
      
      .logo-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 1.8rem;
        font-weight: 700;
        color: var(--primary-color);
      }
    }
    
    .company-info {
      flex-grow: 1;
    }
    
    .company-name {
      font-size: 1.1rem;
      font-weight: 600;
      margin: 0 0 var(--spacing-xs);
    }
    
    .company-meta {
      color: var(--text-secondary);
      font-size: 0.9rem;
      
      span {
        margin-right: var(--spacing-sm);
      }
    }
  }
  
  .company-desc {
    color: var(--text-secondary);
    margin-bottom: var(--spacing-lg);
    line-height: 1.6;
  }
  
  .company-footer {
    text-align: center;
  }
}

// 招聘者卡片
.recruiter-card {
  .card-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0 0 var(--spacing-md);
    padding-bottom: var(--spacing-sm);
    border-bottom: 1px solid var(--border-color);
  }
  
  .recruiter-info {
    display: flex;
    align-items: center;
    margin-bottom: var(--spacing-lg);
    
    .recruiter-avatar {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background-color: var(--primary-color);
      @include flex-center;
      color: white;
      font-weight: 600;
      font-size: 1.5rem;
      margin-right: var(--spacing-md);
    }
    
    .recruiter-detail {
      flex-grow: 1;
    }
    
    .recruiter-name {
      font-weight: 600;
      margin-bottom: var(--spacing-xs);
    }
    
    .recruiter-position {
      color: var(--text-secondary);
      font-size: 0.9rem;
      margin-bottom: var(--spacing-xs);
    }
    
    .recruiter-response {
      color: var(--text-light);
      font-size: 0.85rem;
      display: flex;
      align-items: center;
      
      .el-icon {
        margin-right: var(--spacing-xs);
      }
    }
  }
  
  .recruiter-footer {
    text-align: center;
    
    .el-button {
      width: 100%;
    }
  }
}

// 统计卡片
.stats-card {
  .card-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin: 0 0 var(--spacing-md);
    padding-bottom: var(--spacing-sm);
    border-bottom: 1px solid var(--border-color);
  }
  
  .stats-list {
    list-style: none;
    padding: 0;
    margin: 0;
  }
  
  .stats-item {
    display: flex;
    justify-content: space-between;
    padding: var(--spacing-sm) 0;
    border-bottom: 1px dashed var(--border-color);
    
    &:last-child {
      border-bottom: none;
    }
    
    .stats-label {
      color: var(--text-secondary);
    }
    
    .stats-value {
      font-weight: 500;
    }
  }
}

// 申请对话框
.apply-form {
  .apply-tip {
    margin-bottom: var(--spacing-md);
    color: var(--text-secondary);
  }
  
  .resume-item {
    margin-bottom: var(--spacing-sm);
    padding: var(--spacing-sm);
    border-radius: var(--border-radius);
    transition: background-color var(--transition-fast);
    
    &:hover {
      background-color: var(--light-color);
    }
    
    .el-tag {
      margin-left: var(--spacing-sm);
    }
  }
}

// 聊天对话框
.chat-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
  }
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 600px;
  
  .chat-header {
    padding: var(--spacing-md) var(--spacing-lg);
    border-bottom: 1px solid var(--border-color);
    
    .chat-title {
      display: flex;
      flex-direction: column;
    }
    
    .job-chat-title {
      font-weight: 600;
      font-size: 1.1rem;
      margin-bottom: var(--spacing-xs);
    }
    
    .company-chat-name {
      color: var(--text-secondary);
      font-size: 0.9rem;
    }
  }
  
  .chat-body {
    flex: 1;
    display: flex;
    overflow: hidden;
    
    .applicant-sidebar {
      width: 240px;
      border-right: 1px solid var(--border-color);
      display: flex;
      flex-direction: column;
      
      .sidebar-header {
        padding: var(--spacing-md);
        border-bottom: 1px solid var(--border-color);
        
        .sidebar-title {
          font-size: 1rem;
          font-weight: 600;
          color: var(--text-primary);
        }
      }
      
      .applicant-list-sidebar {
        flex: 1;
        overflow-y: auto;
        padding: var(--spacing-xs);
        
        .applicant-item-sidebar {
          display: flex;
          align-items: center;
          padding: var(--spacing-sm);
          cursor: pointer;
          border-radius: 8px;
          margin-bottom: var(--spacing-xs);
          transition: all 0.2s ease;
          
          &:hover {
            background-color: #f5f7fa;
          }
          
          &.active {
            background-color: #ecf5ff;
            color: var(--color-primary);
          }
          
          .applicant-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: var(--secondary-color);
            @include flex-center;
            color: white;
            font-weight: 600;
            margin-right: var(--spacing-sm);
            flex-shrink: 0;
          }
          
          .applicant-info {
            flex-grow: 1;
            overflow: hidden;
            
            .applicant-name {
              font-weight: 500;
              margin-bottom: 2px;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            
            .applicant-time {
              font-size: 0.8rem;
              color: var(--text-light);
            }
          }
        }
      }
    }
    
    .chat-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      
      .current-chat-indicator {
        padding: var(--spacing-md) var(--spacing-lg);
        background-color: var(--light-color);
        border-bottom: 1px solid var(--border-color);
        
        .highlight-user {
          font-weight: 600;
          color: var(--color-primary);
        }
      }
      
      .chat-messages {
        flex: 1;
        overflow-y: auto;
        padding: var(--spacing-md) var(--spacing-lg);
        
        .message-list {
          display: flex;
          flex-direction: column;
        }
        
        .message-item {
          display: flex;
          margin-bottom: var(--spacing-md);
          
          &.self {
            flex-direction: row-reverse;
            
            .message-avatar {
              margin-left: var(--spacing-md);
              margin-right: 0;
              background-color: var(--primary-color);
            }
            
            .message-content {
              align-items: flex-end;
              
              .message-text {
                background-color: var(--primary-color);
                color: white;
                border-radius: 12px 4px 12px 12px;
              }
            }
          }
          
          &.highlighted {
            .message-avatar {
              background-color: var(--primary-color);
            }
            
            .message-content {
              .message-text {
                background-color: var(--primary-color);
                color: white;
                border-radius: 12px 4px 12px 12px;
              }
            }
          }
          
          &.other-conversation {
            opacity: 0.6;
            
            .message-content {
              .message-text {
                background-color: #f0f0f0;
              }
            }
          }
        }
        
        .message-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: var(--secondary-color);
          @include flex-center;
          color: white;
          font-weight: 600;
          margin-right: var(--spacing-md);
          flex-shrink: 0;
        }
        
        .message-content {
          display: flex;
          flex-direction: column;
          align-items: flex-start;
          max-width: 70%;
        }
        
        .message-sender {
          font-size: 0.85rem;
          color: var(--text-light);
          margin-bottom: 3px;
        }
        
        .message-text {
          padding: var(--spacing-sm) var(--spacing-md);
          background-color: var(--light-color);
          border-radius: 4px 12px 12px 12px;
          word-break: break-word;
        }
        
        .message-time {
          font-size: 0.8rem;
          color: var(--text-light);
          margin-top: 3px;
        }
      }
      
      .chat-input {
        padding: var(--spacing-md) var(--spacing-lg);
        border-top: 1px solid var(--border-color);
        
        .input-actions {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-top: var(--spacing-sm);
          
          .input-tip {
            color: var(--text-light);
            font-size: 0.85rem;
          }
        }
      }
    }
  }
}

.recruiter-sidebar {
  width: 240px;
  border-right: 1px solid var(--border-color);
  display: flex;
  flex-direction: column;
  
  .sidebar-header {
    padding: var(--spacing-md);
    border-bottom: 1px solid var(--border-color);
    
    .sidebar-title {
      font-size: 1rem;
      font-weight: 600;
      color: var(--text-primary);
    }
  }
  
  .recruiter-profile {
    padding: var(--spacing-md);
    display: flex;
    align-items: center;
    border-bottom: 1px solid var(--border-color);
    
    .recruiter-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background-color: var(--primary-color);
      @include flex-center;
      color: white;
      font-weight: 600;
      font-size: 1.5rem;
      margin-right: var(--spacing-md);
    }
    
    .recruiter-info {
      .recruiter-name {
        font-weight: 600;
        margin-bottom: 4px;
      }
      
      .recruiter-position {
        font-size: 0.9rem;
        color: var(--text-secondary);
      }
    }
  }
  
  .job-brief {
    padding: var(--spacing-md);
    
    .brief-header {
      font-weight: 600;
      margin-bottom: var(--spacing-sm);
      font-size: 1rem;
      color: var(--text-primary);
      padding-bottom: var(--spacing-xs);
      border-bottom: 1px dashed var(--border-color);
    }
    
    .brief-title {
      font-weight: 600;
      margin-bottom: 4px;
      color: var(--text-primary);
    }
    
    .brief-company {
      font-size: 0.9rem;
      color: var(--text-secondary);
      margin-bottom: 4px;
    }
    
    .brief-salary {
      font-size: 1rem;
      color: var(--accent-color);
      font-weight: 500;
    }
  }
}
</style> 